package com.goodfox.web.generic.provide.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	public static String format(java.util.Date date, String format) {
		String result = "";
		try {
			if (date != null) {
				DateFormat df = new SimpleDateFormat(format);
				result = df.format(date);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public static Date dateFormat(String dateStr,String format){
		Date date = null;
		try
		{
			DateFormat dateFormat = new SimpleDateFormat(format);
			date = dateFormat.parse(dateStr);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return date;
	}
	public static Date toDate(Date date, String format){
		DateFormat dateFormat = new SimpleDateFormat(format);
		String dateStr = null;
		Date result = null;
			try {
				dateStr = dateFormat.format(date);
				result = dateFormat.parse(dateStr);
			} catch (ParseException e) {
				e.printStackTrace();
			}
	
		return result;
	}

	/**
	 * 返回年份
	 * @param date 日期
	 * @return 返回年份
	 */
	public static int getYear(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.YEAR);
	}

	/**
	 * 返回月份
	 * @param date 日期
	 * @return 返回月份
	 */
	public static int getMonth(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.MONTH) + 1;
	}

	/**
	 * 返回日份
	 * @param date 日期
	 * @return 返回日份
	 */
	public static int getDay(java.util.Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.get(java.util.Calendar.DAY_OF_MONTH);
	}
	
	/**
	 * 判断是否是闰年
	 * @param yearStr 年份
	 * @return  true:闰年 false:平年
	 */
	public static boolean isLeapYear(String yearStr) {
		int year = Integer.parseInt(yearStr);
		if (year % 4 == 0) {
			if (year % 100 == 0) {
				if (year % 400 == 0) {
					return true;
				} else {
					return false;
				}
			} else {
				return true;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 某年的某月的天数
	 * @param yearStr 年份
	 * @param monthStr 月份
	 * @return 该月天数
	 */
	public static int monthHasDay(String yearStr ,String monthStr) {
		int month = Integer.parseInt(monthStr);
		int day;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			day = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			day = 30;
			break;
		case 2:
			if(isLeapYear(yearStr)) {
				day = 29;
			} else {
				day = 28;
			}
			break;
		default:
			day = 0;
			break;
		}
		
		return day;
	}
	
}
